package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.modules.common.excel.common.anno.base.IsCardId;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.utils.CommonUtils;

import java.lang.reflect.Field;

/**
 * @author wang.yishu
 * @version 1.0
 * @className IsCardId
 * @description 是否是身份证号
 * @date 2022/7/11 16:05
 */
public class IsCardIdValidator extends AbstractValidator {

    private IsCardId isCardId;

    @Override
    public boolean canValidate(Field field) {
        isCardId = field.getDeclaredAnnotation(IsCardId.class);
        return isCardId != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        field.setAccessible(true);
        try {
            Object cardIdValue = field.get(entity);
            if (cardIdValue == null) return null;
            if (cardIdValue instanceof String) {
                String cardIdStr = cardIdValue.toString();
                if (!CommonUtils.isIDNumber(cardIdStr)) {
                    return isCardId.msg();
                }
            } else {
                return isCardId.msg();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
